package com.studio5704website.api.security;

import com.studio5704website.application.data.RoleWithToken;
import com.studio5704website.core.security.AuthenticationType;
import com.studio5704website.core.security.UrlPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;

/**
 * @author 高威
 * 角色权限拦截
 */
@Component("rbacAuthorityService")
public class RbacAuthorityService implements AccessService {
    private UrlPermission urlPermission;

    @Autowired
    public RbacAuthorityService(@Qualifier("redisUrlPermission") UrlPermission urlPermission) {
        this.urlPermission = urlPermission;
    }


    @Override
    public boolean hasPermit(HttpServletRequest request, Authentication auth) {
        boolean hasMatch = false;
        boolean hasPermit = false;
        // 这里改为从redis里读取permission信息。
        Map<String, String> table = urlPermission.getUrlPermission();
        RoleWithToken user = null;
        if (auth.getPrincipal() instanceof RoleWithToken) {
            user = (RoleWithToken) auth.getPrincipal();

        } else {
            user = new RoleWithToken();
            user.setPermission("TOURIST");
        }
        String userPermission = user.getPermission();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        Iterator iter = table.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String url = (String) entry.getKey();
            String urlPermission = (String) entry.getValue();
            if (antPathMatcher.match(url ,request.getRequestURI())) {
                hasMatch = true;
                if (AuthenticationType.getType(userPermission) >= AuthenticationType.getType(urlPermission)) {
                    hasPermit = true;
                } else {
                    hasPermit = false;
                }
            }
        }
        if (hasMatch == false) {
            hasPermit = true;
        }
        return hasPermit;
    }
}
